/*
	proc_cleanup.c

	contains the cleanup process's functionality

	Author: Aidan Goddard 25/7/13
*/

#include"headers/scheduler_tables.h"
#include"headers/process_control.h"
#include"../klib/headers/klib_ACDM.h"
#include"../klib/headers/klib_proc_threads.h"

/*
	entry point
*/
uint64_t proc_proc_manager(void)
{
	// the task of this process is to periodically deallocate system resources from processes marked as 'Terminated'
	// enter main loop
	while(1)
	{
		// sleep for 1 second
		__KLIB__SleepThisThread(1000000);

		// then check if there are any processes that require attention
		// enter process loop
		while(1)
		{
			// find a process
			uint64_t PID = 0;
			uint32_t p, i;
			SCH_PCB *pcbs = (SCH_PCB*)(SCHEDULER->PCB);

			// check all the processes (except IDLE process)
			for(i = 1; i < 2048; i++)
			{
				// check its state
				if(pcbs[i].state == PROCESS_STATE_TERMINATED)
				{
					PID = pcbs[i].PID;
					p = i;
					break;
				}
			}

			// was one found?
			if(PID == 0)
			{
				// no, finished this round
				break;
			}

			// yes, one was found

			// deallocate all physical 2M pages

			// now mark process as free and deallocate its PCB
			pcbs[p].state = PROCESS_STATE_UNUSED;
			ReleasePCB(p);

		}

	}

	// somehow got here, send error to system log and kill the process.
	ACDMPrintLog("ERROR: PROCESS MANAGER PROCESS UNEXPECTED TERMINATION", 54);
	__KLIB__KillThisProcess(-1);
}
